 /*
    MegaShorter, the ultimate url-shorting tool
    Copyright (C) 2011  Ivan I. Kolesnikov

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "manager.h"

Manager::Manager(QObject *parent) :
    QObject(parent)
{
    settings = QSharedPointer<QSettings>(new QSettings(QSettings::IniFormat,QSettings::UserScope,"Vd","MegaShorter"), &QObject::deleteLater);
    tray.reset(new QSystemTrayIcon());
    factory.reset(new ShorterFactory(settings));
    mainMenu.reset(new QMenu());

    createMenus();

    tray->setContextMenu(mainMenu.data());
    tray->setIcon(QIcon(":/icons/app"));
    tray->show();

    connect(tray.data(),SIGNAL(activated(QSystemTrayIcon::ActivationReason)),SLOT(trayActivated(QSystemTrayIcon::ActivationReason)));
    connect(qApp->clipboard(),SIGNAL(dataChanged()),SLOT(clipboardChanged()));
}

void Manager::createMenus()
{
    settings->beginGroup("Global");

    mainMenu->addAction(QIcon(),"MegaShorter");
    mainMenu->addAction(QIcon(),"Version 0.1");
    mainMenu->addSeparator();

    QMenu *servicesMenu = mainMenu->addMenu(tr("Active service"));
    servicesGroup.reset(new QActionGroup(servicesMenu));
    connect(servicesGroup.data(), SIGNAL(triggered(QAction*)), SLOT(settingsChanged()));

    QMenu *settingsMenu = mainMenu->addMenu(tr("Settings"));
    settingsMenu->setIcon(QIcon(":/icons/settings"));

    clipboardAction = settingsMenu->addAction(tr("React on clipboard(Ctrl+C, Ctrl+C)"));
    clipboardAction->setCheckable(true);
    clipboardAction->setChecked(settings->value("ReactOnClipboard").toBool());
    connect(clipboardAction, SIGNAL(triggered()), SLOT(settingsChanged()));

    //useRegSvcsAction = settingsMenu->addAction(tr("Use Services with registration(TODO)"));
    //useRegSvcsAction->setCheckable(true);
    //useRegSvcsAction->setChecked(settings->value("UseServicesNeedsApiKeys").toBool());
    //connect(useRegSvcsAction, SIGNAL(triggered()), SLOT(settingsChanged()));

    saveLinksAction = settingsMenu->addAction(tr("Save links to local backup file"));
    saveLinksAction->setCheckable(true);
    saveLinksAction->setChecked(settings->value("SaveLinkList").toBool());
    connect(saveLinksAction, SIGNAL(triggered()), SLOT(settingsChanged()));

    mainMenu->addSeparator();
    mainMenu->addAction(QIcon(":/icons/exit"),"Quit",this,SLOT(exitAction()));

    QStringList shortersList(factory->shorters());

    QString selected = settings->value("DefaultService","").toString();

    for (int i = 0; i < shortersList.size(); i++)
    {
        QAction *action;
        action = servicesMenu->addAction(shortersList[i]);
        action->setCheckable(true);
        action->setData(QVariant(i));
        if (shortersList[i] == selected)
            action->setChecked(true);
        action->setActionGroup(servicesGroup.data());
    }

    currentShorter = factory->getShorter(selected);
    if (currentShorter)
        connect(currentShorter.data(), SIGNAL(done(int,QString,QString)), SLOT(shorterDone(int,QString,QString)));

    settings->endGroup();
}

void Manager::doShort(const QString &s)
{
    if (currentShorter)
        currentShorter->shortLink(QUrl(s));
    else
        tray->showMessage(tr("Error"), tr("Please choice shorter service"), QSystemTrayIcon::Warning, 2000);
}

void Manager::exitAction()
{
    emit deleteLater();
}

void Manager::settingsChanged()
{
    settings->beginGroup("Global");
    if (servicesGroup->checkedAction())
        settings->setValue("DefaultService", servicesGroup->checkedAction()->text());
    settings->setValue("ReactOnClipboard", clipboardAction->isChecked());
    //settings->setValue("UseServicesNeedsApiKeys", useRegSvcsAction->isChecked());
    settings->setValue("SaveLinkList", saveLinksAction->isChecked());
    settings->endGroup();

    if (servicesGroup->checkedAction())
        currentShorter = factory->getShorter(servicesGroup->checkedAction()->text());
    if (currentShorter)
        connect(currentShorter.data(), SIGNAL(done(int,QString,QString)), SLOT(shorterDone(int,QString,QString)));
}

void Manager::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason != QSystemTrayIcon::Trigger)
        return;
    doShort(qApp->clipboard()->text());
}

void Manager::clipboardChanged()
{
    if (! clipboardAction->isChecked()) return;

    qint64 msecs = clipboardTempDT.msecsTo(QDateTime::currentDateTime());

    if (msecs < 500)
    {
        doShort(qApp->clipboard()->text());
        clipboardTempDT = QDateTime();
        return;
    }

    clipboardTempDT = QDateTime::currentDateTime();
}

void Manager::shorterDone(int status, QString req, QString msg)
{
    if (status == Shorter::Ok)
    {
        qApp->clipboard()->setText(msg);
        tray->showMessage(tr("Short link"), msg, QSystemTrayIcon::Information, 1000);
        if (saveLinksAction->isChecked())
            saveLink(msg, req);
    } else
        tray->showMessage(tr("Error"), msg, QSystemTrayIcon::Warning, 2000);
}

void Manager::saveLink(const QString &shortUrl, const QString &longUrl)
{
    QString docDirStr(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation));
    QDir docDir(docDirStr);
    if (! docDir.cd("MegaShorter"))
    {
        docDir.mkdir("MegaShorter");
        if (! docDir.cd("MegaShorter"))
        {
            tray->showMessage(tr("Error"), "Can't create MegaShorter dir in Documents", QSystemTrayIcon::Warning, 2000);
            return;
        }
    }

    QString fileName = QDateTime::currentDateTime().toString("yyyy-MM-dd") + ".log";

    QFile file(docDir.absoluteFilePath(fileName));
    if (! file.open(QIODevice::Append))
    {
        tray->showMessage(tr("Error"), "Can't write backup-file to Documents", QSystemTrayIcon::Warning, 2000);
        return;
    }

    QString dateTime(QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss.zzz"));

    file.write(QString(dateTime + " - " + shortUrl + " - " + longUrl.trimmed() + "\n").toUtf8());
    file.close();

}
